<template>
  <div>
    <div>
      <el-row :gutter="20">
        <div
          style="background-color: #fefefe; padding: 5px 5px 0px 5px;border-radius: 1px; border-bottom: 1px solid #EEEEEE; ">
          <el-row :gutter="20" style="line-height: 35px;">
            <el-col style="width: 300px;display: flex;">
              <div class="item_label">开票区间:</div>
              <el-date-picker type="daterange" v-model="filterData.daterange" size="mini" start-placeholder="起始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" range-separator="至"
                style="width: 100%;"></el-date-picker>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">销项票号码:</div>
              <el-input v-model="filterData.fphm" style="width: 100%;" placeholder="销项数电票号码或纸质发票号码" size="mini"
                clearable></el-input>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">购方名称:</div>
              <el-select v-model="filterData.buyer" style="width: 100%;" size="mini" placeholder="购方名称" filterable allow-create
                clearable>
                <el-option v-for="(item,index) in buyerlist" :label="item.title" :value="item.title" :key="index">
                </el-option>
              </el-select>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">票面总额:</div>
              <el-input v-model="filterData.sum" style="width: 100%;" placeholder="票面总额" size="mini"
                clearable></el-input>
            </el-col>


            <el-col style="width: 300px;display: flex;">
              <div class="item_label">发票类型:</div>
              <el-select v-model="filterData.type" placeholder="发票类型" size="mini" clearable style="width: 100%;">
                <el-option label="增值税普票" value="增值税普票"></el-option>
                <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
              </el-select>
            </el-col>

            <el-col style="width: 200px;display: flex;">
              <div class="item_label">发票状态:</div>
              <el-select v-model="filterData.status" placeholder="发票状态" size="mini" clearable style="width: 100%;">
                <el-option label="正常" value="1"></el-option>
                <el-option label="作废" value="0"></el-option>
                <el-option label="红冲" value="2"></el-option>
              </el-select>
            </el-col>

            <el-col style="width: 300px;display: flex;line-height: 30px;">
                <div class="item_label">所属账套:</div>
                <el-select v-model="filterData.seller" filterable placeholder="账套" style="width: 100%;" clearable>
                  <el-option :label="item.name" :value="item.name" v-for="(item,index) in accounts" :key="index"></el-option>
                </el-select>
             </el-col>


            <el-col style="width: 300px;display: flex;">
              <div class="item_label">进项发票号:</div>
              <el-input v-model="filterData.buyfphm" style="width: 100%;" placeholder="进项数电票号码或纸质发票号码" size="mini"
                clearable></el-input>
            </el-col>


            <el-col style="width: 200px;display: flex;">
              <div class="item_label">进项绑定:</div>
              <el-select v-model="filterData.buystatus" placeholder="进项绑定" size="mini" clearable style="width: 100%;"
                clearable>
                <el-option label="不完整" value="0"></el-option>
                <el-option label="完整" value="1"></el-option>
              </el-select>
            </el-col>



            <el-col style="width: 300px;display: flex;">
              <div class="item_label">销项票备注:</div>
              <el-input v-model="filterData.memo" style="width: 100%;" placeholder="销项票备注" size="mini"
                clearable></el-input>
            </el-col>

            <el-col style="width: 200px;display: flex;">
              <el-button type="primary" icon="el-icon-search" @click="currentRow=null; curpage=1; loadDataList()"
                size="mini">查询发票</el-button>
            </el-col>
          </el-row>
        </div>
      </el-row>
    </div>

    <div class="table-wraper">
      <div style="padding: 5px 0px; display: flex;">
        <div style="flex: 1px;">
          <el-button-group>
            <el-button type="primary" @click="handleCreate" size="mini" icon="el-icon-plus">录入销项发票</el-button>
          </el-button-group>
        </div>
        <div style="text-align: right;">
          <div style="margin-bottom: 5px;">
          <el-dropdown split-button type="primary" size="mini" @command="handleExport">
            导出表格
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="export_check" disabled  v-if="selection.length<=0" >导出选中项</el-dropdown-item>
                <el-dropdown-item command="export_check" v-if="selection.length>0" >导出选中项</el-dropdown-item>
                <el-dropdown-item command="export_all">导出全部</el-dropdown-item>
               </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div>

        </div>
      </div>
      <div style="height: 350px">
        <el-table :data="tableData" ref="tickettable" border height="100%" empty-text="暂无发票或未查询到相关发票信息"
          @select="handleSelection" @select-all="handleSelection" @row-click="handleTicketRowClick"
          highlight-current-row :header-cell-style="{'background-color': '#f5f7f9','color':'#3e3e3e'}">
          <el-table-column label="" type="selection" align="center"></el-table-column>
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="状态" prop="status" width="60px" align="center">
            <template v-slot="scope">
              <span v-if="scope.row.status=='1'"
                style="background-color:#00bc00;color:#FFFFFF;padding: 2px 5px;">正常</span>
              <span v-if="scope.row.status=='0'"
                style="background-color:#a5a5a5;color:#FFFFFF;padding: 2px 5px;">作废</span>
              <span v-if="scope.row.status=='2'"
                style="background-color:#ffaa00;color:#FFFFFF;padding: 2px 5px;">红冲</span>

            </template>
          </el-table-column>
          <el-table-column label="开票日期" prop="date" width="140px" align="center"></el-table-column>
          <el-table-column label="发票号码或数电票号" prop="fphm" width="160px" align="center"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="发票类型" prop="type" width="100px" align="center"></el-table-column>
          <el-table-column label="购方名称" prop="buyer" width="180px" show-overflow-tooltip></el-table-column>
          <el-table-column label="金额" prop="total" width="120px" align="center"></el-table-column>
          <el-table-column label="税额" prop="tax" width="90px" align="center"></el-table-column>
          <el-table-column label="价税总额" prop="sum" width="120px" align="center"></el-table-column>
          <el-table-column label="备注" prop="memo" show-overflow-tooltip></el-table-column>
          <el-table-column label="关联进项" align="center">
            <el-table-column label="进项票号" prop="buyticket_bindnum1" width="120px" show-overflow-tooltip align="center"></el-table-column>
            <el-table-column label="状态" width="75px" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.buyticket_bindstatus1==0" style="color: #ff5500;">不完整</span>
                <span v-if="scope.row.buyticket_bindstatus1==1" style="color:#00bc00">完整</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="附件" align="center" v-if="false">
            <template v-slot="scope">
              <div style="display: flex;" @click="handlePreviewAttach(scope.$index,scope.row)">
                <div v-for="(item,index) in scope.row.attach"
                  style="padding: 1px; margin:1px;background-color: #b8b8b8;width: 22px;height:22px;">
                  <img v-if="item.type.indexOf('image')!=-1" :src="item.url" style="width: 20px;height:20px;">
                  <img v-if="item.type.indexOf('pdf')!=-1" src="@/assets/images/icon_pdf.jpg"
                    style="width: 20px;height:20px;">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="所属账套" align="center" prop="seller" width="150px" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="130px" align="center" fixed="right">
            <template v-slot="scope">
              <el-button-group>
                <el-button size="mini" icon="el-icon-edit-outline" title="编辑发票基本信息" circle
                  @click="handleEdit(scope.$index,scope.row)" />
                <el-button size="mini" icon="el-icon-view" circle title="查看发票明细"
                  @click="handleDetail(scope.$index,scope.row)" />
                <el-button size="mini" icon="el-icon-link" circle title="查看发票附件" v-if="scope.row.attach.length>0"
                  @click="handlePreviewAttach(scope.$index,scope.row)" />
                <el-button size="mini" type="danger" icon="el-icon-delete" circle
                  @click="handleDelete(scope.$index,scope.row)" />
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <div style="float: left;height:30px;line-height: 30px;">
          <span style="margin-right: 20px;">非税金额:{{parseFloat(sum_total).toFixed(2)}}</span>
          <span style="margin-right: 20px;">税额:{{parseFloat(sum_tax).toFixed(2)}}</span>
          <span style="margin-right: 20px;">含税总额:{{parseFloat(sum_sum).toFixed(2)}}</span>
          <span style="margin-right: 20px;">选中金额:{{parseFloat(sum_selection).toFixed(2)}}</span>
        </div>

        <div style="text-align: right;">
          <el-pagination layout=" prev, pager,next,sizes,total" :total="numrows" :page-size="pagesize"
            :current-page="curpage" prev-text="上一页" next-text="下一页" :page-sizes="[15, 25, 30]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
      <div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="title">销项明细</div>
            <el-empty description="请点击选择要查看的发票" v-if="!currentRow"></el-empty>
            <div v-if="currentRow">
              <div style="text-align: right;">
                <el-button icon="el-icon-view" size="mini" v-if="currentRow.attach.length>0"
                  @click="handlePreviewAttach(-1,currentRow)" type="primary">查看附件</el-button>
              </div>
              <div style="text-align: center; font-size: 16px; font-weight: bold;">{{currentRow.type}}</div>
              <div style="display: flex;">
                <div style="line-height: 25px;flex: 1;">购方单位:{{currentRow.buyer}}</div>
                <div style="line-height: 25px;flex: 1">开票日期:{{currentRow.date}}</div>
                <div style="line-height: 25px;flex: 1; text-align: right;">发票号码:{{currentRow.fphm}}</div>
              </div>
              <div style="height: 220px; overflow-y: auto;">
                <el-table :data="currentRow.goods" border height="100%">
                  <el-table-column label="序号" type="index" align="center"></el-table-column>
                  <el-table-column label="项目名称" prop="title" width="150px" show-overflow-tooltip>
                    <template v-slot="scope">
                      *{{scope.row.taxname}}*{{scope.row.title}}
                    </template>
                  </el-table-column>
                  <el-table-column label="规格型号" prop="model" show-overflow-tooltip></el-table-column>
                  <el-table-column label="单位" prop="unit" width="90px" align="center"></el-table-column>
                  <el-table-column label="数量" prop="count" width="60px" align="center"></el-table-column>
                  <el-table-column label="单价" prop="price" align="center" show-overflow-tooltip></el-table-column>
                  <el-table-column label="金额" prop="total" align="center"></el-table-column>
                  <el-table-column label="税率" prop="rate" width="60px" align="center">
                    <template v-slot="scope">
                      {{scope.row.rate*100}}%
                    </template>
                  </el-table-column>
                  <el-table-column label="税额" prop="tax" align="center"></el-table-column>
                  <el-table-column label="价税金额" prop="sum" align="center"></el-table-column>
                </el-table>
              </div>
              <div style="display: flex;">
                <div style="flex: 1;">
                  销售单位:{{currentRow.seller}}
                </div>
                <div style="text-align: right;">
                  <span style="width: 200px; margin-left:20px;">金额:{{currentRow.total}}</span>
                  <span style="width: 200px;margin-left:20px;">税额:{{currentRow.tax}}</span>
                  <span style="width: 200px; margin-left:20px;">价税总额:{{currentRow.sum}}</span>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="title">进项绑定</div>

          </el-col>
        </el-row>
      </div>
    </div>
    <CreateUI ref="createUI" v-if="createVisible" @completeHandler="handleCreateCallback" />
    <AttachUI ref="attachUI" v-if="attachVisible" />
    <EditUI ref="editUI" v-if="editVisible" @completeHandler="handleEditCallback"></EditUI>
    <DetailUI ref="detailUI" v-if="detailVisible"></DetailUI>
  </div>
</template>

<script>
  import CreateUI from './create.vue'
  import AttachUI from '@/components/attachviewer.vue'
  import EditUI from './edit.vue';
  import DetailUI from './detailview.vue';
  export default {
    components: {
      CreateUI,
      AttachUI,
      EditUI,
      DetailUI,
    },
    data() {
      return {
        buyerlist: [],
        sellerlist: [],
        filterData: {
          daterange: '',
          status: '',
          type: '',
          buyer: '',
          seller: '',
          sum: '',
          bindstatus: '',
          fphm: '',
          bindfphm: '',
          memo: '',
          good: ''
        },
        sum_total: 0.00,
        sum_tax: 0,
        sum_sum: 0,
        currentRow: null,
        accounts:[],
        sum_selection: 0,
        selection: [],
        list: [],
        curpage: 1,
        pagesize: 15,
        numrows: 1,
        tableData: [],
        createVisible: false,
        attachVisible: false,
        editVisible: false,
        detailVisible: false,
        importTxtTicketVisible: false,
      }
    },
    mounted() {
      var now= new Date();
      var firstDay=this.formatDate(new Date(now.getFullYear(),now.getMonth(),1));
      var lastDay=this.formatDate(new Date(now.getFullYear(),now.getMonth()+1,0));
      this.filterData.daterange = [firstDay,lastDay];

      this.loadDataList();
      this.loadBuyerList();
      this.loadSellerList();
      this.loadAccounts();
    },
    methods: {
      formatDate(date) {
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        const dd = String(date.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
      },
      loadAccounts(){
        this.axios.post("api/admin/account/list").then(res=>{
          if(res.status==200&& res.data.code==0){
             this.accounts=res.data.list;
          }
        })
      },
      loadBuyerList() {
        this.axios.post("api/admin/client/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.buyerlist = res.data.list;
          }
        });
      },
      loadSellerList() {
        this.axios.post("api/admin/buysupplier/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.sellerlist = res.data.list;
          }
        });
      },
      handleTicketRowClick(row, column, event) {
        this.currentRow = row;
      },
      handleAutoImportCallback(ticket) {
        this.createVisible = true;
        this.$nextTick(() => {
          this.$refs.createUI.dialogVisible = true;
          this.$refs.createUI.autoImport(ticket);
        })
      },
      handleExport(cmd){
        switch(cmd){
          case "export_all":
          this.handleExportAll();
          break;
          case "export_check":
          this.handleExportChecks();
          break;
        }
      },
      handleExportChecks(){
        //导出excel
         var index=1;
         let slist=this.selection.map((item)=>{
           let obj={
             "序号":index,
             "状态":item.status==1? (item.status==2? "红冲":"正常"):"作废",
             "开票日期":item.date,
             "发票类型":item.type,
             "购买单位名称":item.buyer,
             "销项票号":item.fphm,
             "销项代码":item.fpdm,
             "金额":item.total,
             "税额":item.tax,
             "价税总额":item.sum,
             "备注":item.memo,
             "关联进项状态":item.buyticket_bindstatus1=="0"? '不完整':"完整",
             "关联进项总额":item.buyticket_bindrmb1,
             "关联进项发票号":item.buyticket_bindnum1,
             "关联进项备注":item.bind_buystatusmemo,
             "所属账套":item.seller,
           }
           index++;
           return obj;
         });
        let ws= XLSX.utils.json_to_sheet(slist,{skipHeader:false});
         ws["!cols"]=[{wpx:80}];
         let wb=XLSX.utils.book_new();
         XLSX.utils.book_append_sheet(wb,ws,'销售发票');
         XLSX.writeFile(wb,"导出销售发票"+this.CurrentDateTime()+".xlsx");
      },
      handleExportAll(){
        var params = {
            status: this.filterData.status,
            type: this.filterData.type,
            buyer: this.filterData.buyer,
            fphm: this.filterData.fphm,
            buyfphm: this.filterData.buyfphm,
            sum: this.filterData.sum,
            memo: this.filterData.memo,
            buystatus: this.filterData.buystatus,
            seller: this.filterData.seller,
            curpage: this.curpage,
            pagesize: this.pagesize,
            daterange: this.filterData.daterange
          }
          this.axios.post("api/admin/saleticket/export", params).then((res) => {
            if (res.status == 200 && res.data.code) {

              //导出excel
               var index=1;
               let slist=res.data.list.map((item)=>{
                 let obj={
                   "序号":index,
                   "状态":item.status==1? (item.status==2? "红冲":"正常"):"作废",
                   "开票日期":item.date,
                   "发票类型":item.type,
                   "购买单位名称":item.buyer,
                   "销项票号":item.fphm,
                   "销项代码":item.fpdm,
                   "金额":item.total,
                   "税额":item.tax,
                   "价税总额":item.sum,
                   "备注":item.memo,
                   "关联进项状态":item.buyticket_bindstatus1=="0"? '不完整':"完整",
                   "关联进项总额":item.buyticket_bindrmb1,
                   "关联进项发票号":item.buyticket_bindnum1,
                   "关联进项备注":item.bind_buystatusmemo,
                   "所属账套":item.seller,

                 }
                 index++;
                 return obj;
               });
              let ws= XLSX.utils.json_to_sheet(slist,{skipHeader:false});
               ws["!cols"]=[{wpx:80}];
               let wb=XLSX.utils.book_new();
               XLSX.utils.book_append_sheet(wb,ws,'销售发票');
               var dt=
               XLSX.writeFile(wb,"导出销售发票"+this.CurrentDateTime()+".xlsx");

            }
          });
      },
      handleBind(index, data) {



      },

      handleImportExcel(file, filelist) {
        var fd = new FormData();
        fd.append("_file", file.raw);
        this.$axiosUploader.post("api/admin/saleticket/import", fd).then(res => {

          console.log(res);

        });



        console.log(file, filelist);
        return;

        var _this = this;
        var reader = new FileReader();
        reader.onload = function(e) {
          var data = e.target.result;
          var workbook = XLSX.read(data, {
            type: 'binary',
            cellStyles: true
          });
          var rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {
            header: 1,
            range: 1
          });
          console.log(rows);
        }
        reader.readAsBinaryString(file.raw);
      },
      handleSelection(list) {
        this.selection = list;
        this.sum_selection = 0;
        list.map((item) => {
          this.sum_selection += parseFloat(item.sum);
        })
      },
      handlePreviewAttach(index, data) {
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.initData(JSON.parse(JSON.stringify(data.attach)));
        })
      },
      handleDetail(index, data) {
        this.detailVisible = true;
        this.$nextTick(() => {
          this.$refs.detailUI.dialogVisible = true;
          this.$refs.detailUI.init(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handleImportText() {
        this.importTxtTicketVisible = true;
        this.$nextTick(() => {
          this.$refs.importTxtTicketUI.dialogVisible = true;
          this.$refs.importTxtTicketUI.initData();
        })
      },
      format2Number(value, len) {
        var f = parseFloat(value);
        return f.toFixed(len);
      },
      handleSizeChange: function(val) {
        this.pagesize = val;
        this.curpage = 1;
        this.loadDataList();
      },
      handleCurrentChange: function(val) {
        this.curpage = parseInt(val);
        this.loadDataList();
      },
      handleDelete(index, data) {
        //是否要删除此发票
        this.$confirm("确定要删除【" + data.fphm + "】销项发票吗?", "确认", {
          type: 'warning'
        }).then(() => {
          this.axios.post("api/admin/saleticket/delete", {
            id: data.id
          }).then(res => {
            if (res.status == 200 && res.data.code == 1) {
              this.$message.success({
                message: res.data.msg,
                duration: 1500,
                showClose: true
              });
              this.loadDataList();
            } else {
              this.$message.error({
                message: res.data.msg,
                duration: 1500,
                showClose: true
              });
            }

          })
        }).catch(er => {

        })

      },
      loadDataList() {
        var params = {
          status: this.filterData.status,
          type: this.filterData.type,
          buyer: this.filterData.buyer,
          fphm: this.filterData.fphm,
          buyfphm: this.filterData.buyfphm,
          sum: this.filterData.sum,
          memo: this.filterData.memo,
          buystatus: this.filterData.buystatus,
          seller: this.filterData.seller,
          curpage: this.curpage,
          pagesize: this.pagesize,
          daterange: this.filterData.daterange
        }
        this.axios.post("api/admin/saleticket/list", params).then((res) => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
            this.numrows = res.data.numrows;
            this.sum_total = res.data.total;
            this.sum_sum = res.data.sum;
            this.sum_tax = res.data.tax;

            if (this.tableData.length > 0) {

            }
          }
        });
      },

      handleEdit(index, data) {
        this.editVisible = true;
        this.$nextTick(() => {
          this.$refs.editUI.dialogVisible = true;
          this.$refs.editUI.init(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handleEditCallback(index, data) {
        this.tableData[index].goods = data.goods;
        this.tableData[index].sum = parseFloat(data.sum).toFixed(2);
        this.tableData[index].total = parseFloat(data.total).toFixed(2);
        this.tableData[index].num = data.num;
        this.tableData[index].type = data.type;
        this.tableData[index].date = data.date;
        this.tableData[index].supname = data.supname;
        this.tableData[index].code = data.code;
        this.tableData[index].tax = data.tax;
        this.tableData[index].memo = data.memo;
        this.tableData[index].attach = data.attach;
        this.tableData[index].status = data.status;
      },

      handleCreate() {
        this.createVisible = true;
        this.$nextTick(() => {
          this.$refs.createUI.dialogVisible = true;
          this.$refs.createUI.initData();
        })
      },
      handleCreateCallback() {
        this.curpage = 1;
        this.loadDataList();
      }
    }
  }
</script>

<style scoped>
  .title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 2px;
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  .title:before {
    content: "";
    position: absolute;
    top: 4px;
    left: 0;
    width: 5px;
    height: 65%;
    background-color: #249af3;
  }


  .item_label {
    text-align: center;
    line-height: 35px;
    margin: 0px 2px;
    width: 95px;
  }
</style>
